package red.ouo.distributedtools.utils;

import org.springframework.util.Assert;
import red.ouo.distributedtools.DistributedToolsApplication;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ReflectUtils {
    /**
     * 获取指定类Spring容器内所有子类
     *
     * @param c
     * @return
     */
    public static Map getAllInterfaceAchieve(Class c) {
        return DistributedToolsApplication.applicationContext.getBeansOfType(c);
    }

    /**
     * 顺序执行一组对象内指定方法
     *
     * @return List<R> 执行结果列
     */
    public static <R> List<R> invokeMethod(List<Object> obs, String methodName, Class[] argsClass, Object... args) {
        List<R> result = new ArrayList<>();
        for (Object ob : obs) {
            try {
                Assert.notNull(ob, "NULL Exception");
                Method method = ob.getClass().getMethod(methodName, argsClass);
                result.add((R) method.invoke(ob, args));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
